<template>
  <div class="global-container">
    <div class="global-header">
      <el-image
        style="width: 100px; height: 100px"
        :src="require('@/assets/header_images/current.png')"
      ></el-image>
      <div class="title">
        持久卷声明
        <div class="title-content">
          提供PVC持久卷管理能力，支持以PVC、PV的创建、删除等功能。
        </div>
      </div>
    </div>
    <div class="searchDiv1">
      <div class="searchDiv global-operate">
        <span class="keyword">关键词：</span>
        <el-input
          v-model="searchInput"
          placeholder="请输入名称进行检索"
          clearable
          class="inputStyle"
          style="width: 20%"
          prefix-icon="el-icon-search"
          @input="filterPvcList"
        />
        <!-- <el-button type="primary" size="small" @click="filterPvcList">查 询</el-button> -->
        <div style="float: right">
          <el-button
            type="primary"
            size="small"
            @click="openCreatePersistentVolumeClaimDialog"
            class="el-button-primary-style"
          >创 建
          </el-button>
          <el-popconfirm
            title="确定删除选中的持久卷声明吗？"
            @confirm="deletePvc"
          >
            <el-button
              slot="reference"
              type="primary"
              size="small"
              class="el-button-primary-style"
              style="margin: 0 10px"
              :disabled="selectPvcList.length === 0"
            >删 除
            </el-button>
          </el-popconfirm>
        </div>
      </div>
    </div>
    <div>
      <div class="servicePackageList">
        <div style="height: 60vh">
          <el-table
            ref="multipleTable"
            :data="tableData"
            style="width: 100%"
            @selection-change="tableSelectionChange"
          >
            <el-table-column type="selection" align="center"/>
            <el-table-column prop="pvcName" label="名称" width="150">
              <template slot-scope="scope">
                <!--                <el-tooltip-->
                <!--                  effect="dark"-->
                <!--                  :content="scope.row.pvcName"-->
                <!--                  placement="bottom"-->
                <!--                  popper-class="tooltipClass"-->
                <!--                >-->
                <!--                  :disabled="isShowTooltip"-->
                <!--                  @mouseover="onMouseOver($event)"-->
                <div class="descSpan">
                  {{ scope.row.pvcName }}
                </div>
                <!--                </el-tooltip>-->
              </template>
            </el-table-column>
            <el-table-column prop="namespace" label="命名空间" width="250"/>
            <el-table-column prop="pvcAccessModes" label="访问模式">
              <template slot="header" slot-scope="scope">
                <span @click="showAccessDetail">
                  {{ scope.column.label }}
                  <i class="el-icon-question" style="margin-left: 5px"></i>
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="pvcCapacity" label="申请容量(GB)"/>
            <el-table-column prop="pvcStatus" label="状态" width="120rem">
              <template slot="header" slot-scope="scope">
                <span @click="showStatusDetail">
                  {{ scope.column.label }}
                  <i class="el-icon-question" style="margin-left: 5px"></i>
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="创建时间"/>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="pvDetail(scope.row)"
                  style="padding: 0"
                >查看持久卷
                </el-button>
                <el-button
                  type="text"
                  @click="showYamlInfo(scope.row)"
                  style="margin-right: 10px; padding: 0"
                >
                  查看yaml
                </el-button>
                <el-popconfirm
                  title="确定删除此持久卷声明吗？"
                  @confirm="deleteCommand(scope.row)"
                >
                  <el-button
                    slot="reference"
                    type="text"
                    style="color: #f56c6c; padding: 0"
                  >删除
                  </el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="margin-top: 10px; float: right">
          <el-pagination
            background
            layout="total, prev, pager, next, jumper"
            :total="page.total"
            :page-size="page.pageSize"
            :page.sync="page"
            @current-change="changePage"
          />
        </div>
      </div>
    </div>
    <div v-if="createPvc">
      <el-dialog
        title="创建持久卷声明"
        :visible.sync="createPvc"
        width="550px"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :before-close="beforeCloseCreateDialog"
      >
        <CreatePersistentVolumeClaim
          ref="createPersistentVolumeClaimRef"
          @complete="handleComplete"
        />
      </el-dialog>
    </div>
    <div v-if="dialogVisible">
      <el-dialog
        title="持久卷"
        :visible.sync="dialogVisible"
        width="70%"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :destroy-on-close="true"
      >
        <PersistentVolume :pvc-id="pvcId"/>
      </el-dialog>
    </div>
    <div v-if="yamlDialog">
      <el-dialog
        title="查看yaml"
        :visible.sync="yamlDialog"
        width="50%"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :destroy-on-close="true"
      >
        <button @click="downloadYaml">下载YAML</button>
        <codemirror v-model="yamlString" :options="cmOptions"/>
      </el-dialog>
    </div>
    <el-dialog
      title="访问模式"
      :visible.sync="accessDialogVisible"
      width="35%"
      @close="accessDialogVisible = false"
    >
      <p class="titleF">1.ReadWriteOnce(单节点读写)</p>
      <p class="titleS">
        PV可以被单个节点以读写方式挂载和访问。这意味着PV只能被一个Pod挂载,并且Pod可以对PV进行读写操作。
      </p>
      <p class="titleF">2.ReadOnlyMany(多节点只读)</p>
      <p class="titleS">
        PV可以被多个节点以只读方式挂载和访问。这意味着PV可以被多个Pod挂载,但这些Pod只能对PV进行读操作,不能进行写操作。
      </p>
      <p class="titleF">3.ReadWriteMany(多节点读写)</p>
      <p class="titleS">
        PV可以被多个节点以读写方式挂载和访问。这意味着PV可以被多个Pod挂载,并且这些Pod可以对PV进行读写操作。
      </p>
    </el-dialog>
    <el-dialog
      title="状态"
      :visible.sync="StatusDialogVisible"
      width="35%"
      @close="StatusDialogVisible = false"
    >
      <p class="titleF">1.Pending(等待中)</p>
      <p class="titleS">
        当创建一个PVC时,如果没有可用的PV与之匹配,PVC的状态将为Pending。
      </p>
      <p class="titleF">2.Bound(已绑定)</p>
      <p class="titleS">当一个可用的PV与PVC成功匹配时,PVC的状态将变为Bound。</p>
      <p class="titleF">3.Lost(丢失)</p>
      <p class="titleS">
        当PVC被删除时,与其相关联的PV也会被自动删除。同时,与PV相关联的底层存储资源也会被删除。
      </p>
      <p class="titleF">4.Failed(失败)</p>
      <p class="titleS">
        如果PVC的创建或绑定过程中发生错误,PVC的状态将变为Failed。
      </p>
    </el-dialog>
  </div>
</template>

<script>
  import CreatePersistentVolumeClaim from "@/views/storageManage/CreatePersistentVolumeClaim.vue";
  import PersistentVolume from "@/views/storageManage/PersistentVolume.vue";
  import {codemirror} from "vue-codemirror";
  import "codemirror/lib/codemirror.css";
  import "codemirror/mode/yaml/yaml.js";
  import {getTenantId} from "@/utils/tenantId";

  export default {
    name: "ServiceList",
    components: {
      CreatePersistentVolumeClaim,
      PersistentVolume,
      codemirror,
    },
    data() {
      return {
        searchInput: "",
        tableData: [],
        selectPvcList: [],
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0,
        },
        tmpPage: {
          pageSize: 10,
          pageNum: 1,
          filterKey: "",
          tenantId: "",
        },
        createPvc: false,
        dialogVisible: false,
        yamlDialog: false,
        yamlString: "",
        pvcId: "",
        yamlName: "",
        pv: [],
        cmOptions: {
          mode: "yaml", // 使用YAML模式
          theme: "default", // 使用默认主题
          lineNumbers: true, // 显示行号
          line: true, // 显示行高亮
          styleActiveLine: true, // 高亮当前行
          matchBrackets: true, // 括号匹配高亮
          autoCloseBrackets: true, // 自动闭合括号
          gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], // 显示行号和折叠标记
          foldGutter: true, // 启用折叠功能
          extraKeys: {"Ctrl-Space": "autocomplete"}, // 添加自动完成快捷键
          readOnly: true, // 禁止编辑
        },
        accessDialogVisible: false,
        StatusDialogVisible: false,
      };
    },
    mounted() {
      this.getAllPvcByPage();
    },
    methods: {
      pvDetail(row) {
        this.$storagePvcApi
          .getPvInfoByPvcId(row.id)
          .then((res) => {
            if (res && res.code === 200) {
              this.pv = res.data;
              this.dialogVisible = true;
              this.pvcId = row.id;
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },

      openCreatePersistentVolumeClaimDialog() {
        this.createPvc = true;
        this.$nextTick(() => {
          if (this.$refs.createPersistentVolumeClaimRef !== undefined) {
            this.$refs.createPersistentVolumeClaimRef.$on(
              "closeCreatePersistentVolumeClaimDialog",
              this.closeCreatePersistentVolumeClaimDialog
            );
          }
        });
      },
      closeCreatePersistentVolumeClaimDialog() {
        this.$refs.createPersistentVolumeClaimRef.$off(
          "closeCreatePersistentVolumeClaimDialog"
        );
        this.beforeCloseCreateDialog();
      },
      // 分页获取所有pvc
      getAllPvcByPage() {
        this.tmpPage.tenantId = getTenantId();
        this.$storagePvcApi
          .listAllPvcByPage(this.tmpPage)
          .then((res) => {
            if (res && res.code === 200) {
              this.tableData = res.data.records;
              this.page.total = res.data.total;
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      // 过滤展示
      filterPvcList() {
        this.tmpPage.filterKey = this.searchInput;
        this.tmpPage.pageNum = 1;
        this.tmpPage.pageSize = 10;
        this.getAllPvcByPage();
      },
      // 更换页数
      changePage(currentPage) {
        this.page.currentPage = currentPage;
        this.tmpPage.pageNum = currentPage;
        this.getAllPvcByPage();
      },

      // 删除pvc
      deletePvc() {
        if (!this.operateCheck()) {
          return;
        }
        const deployIds = [];
        this.selectPvcList.forEach((ele) => {
          deployIds.push(ele.id);
        });
        this.$storagePvcApi
          .deletePvc(deployIds)
          .then((res) => {
            if (res && res.code === 200) {
              this.$message.success(res.msg);
              this.selectPvcList = [];
              this.$refs.multipleTable.clearSelection();
              this.tmpPage.pageSize = this.page.pageSize;
              this.tmpPage.pageNum = this.page.currentPage;
              this.getAllPvcByPage();
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      operateCheck() {
        if (this.selectPvcList.length === 0) {
          this.$message.warning("请选择数据之后点击删除");
          return false;
        }
        return true;
      },

      // 新增pvc
      beforeCloseCreateDialog() {
        this.createPvc = false;
      },
      handleComplete() {
        this.createPvc = false;
        this.getAllPvcByPage();
      },

      // 处理更多
      tableSelectionChange(selectList) {
        this.selectPvcList = selectList;
      },
      showYamlInfo(row) {
        this.yamlDialog = true;
        this.yamlString = row.pvcYaml;
        this.yamlName = row.pvcName;
      },

      showConfirm(row) {
        this.$confirm("确定删除此持久卷声明吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.deleteCommand(row);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      },

      deleteCommand(row) {
        this.$storagePvcApi
          .deletePvc([row.id])
          .then((res) => {
            if (res && res.code === 200) {
              // this.$message.success(res.msg)
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.selectPvcList = [];
              this.$refs.multipleTable.clearSelection();
              this.tmpPage.pageSize = this.page.pageSize;
              this.tmpPage.pageNum = this.page.currentPage;
              this.getAllPvcByPage();
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },

      // 下载yaml文件
      downloadYaml() {
        const blob = new Blob([this.yamlString], {
          type: "text/plain;charset=utf-8",
        }); // 将YAML数据转换为Blob对象
        const url = URL.createObjectURL(blob); // 创建Blob对象的URL
        const link = document.createElement("a"); // 创建一个<a>元素
        link.href = url; // 设置<a>元素的href属性为Blob对象的URL
        link.download = this.yamlName + "_pvc.yaml"; // 设置下载文件的文件名（可选）
        link.click(); // 模拟点击<a>元素进行下载操作
      },
      showAccessDetail() {
        this.accessDialogVisible = true;
      },
      showStatusDetail() {
        this.StatusDialogVisible = true;
      },
    },
  };
</script>

<style lang="css" scoped>
  /* .searchDiv1 {
        height: 80px;
        width: 100%;
        background-color: white;
        display: flex;
        align-items: center;
        border-radius: 10px;
      } */

  /* .searchDiv {
        width: 95%;
        margin-left: 2%;
      } */

  /* .inputStyle {
        width: 200px;
        margin-right: 10px;
      } */

  /* .servicePackageListDiv {
        margin-top: 15px;
        border: 1px solid #2064e6;
        height: 40px;
        width: 100%;
        background-color: #1979fe;
        display: flex;
        justify-content: space-around;
        align-items: center;
      } */

  /* .servicePackageListDivSpan {
        color: white;
        width: 95%;
      } */

  /* .servicePackageList {
        border: 1px solid #2064e6;
        height: 75vh;
        background-color: white;
      } */

  /* .descSpan {
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      } */
</style>

<style lang="css" scoped>
  .tooltipClass {
    width: 200px;
  }

  /*.el-button {*/
  /*  border-radius: 30px;*/
  /*  display: inline-block;*/
  /*  margin: 0 8px;*/
  /*}*/

  .titleF {
    font-size: 16px;
    margin-bottom: 6px;
    color: #409eff;
  }

  .titleS {
    text-indent: 2em;
    color: #304156;
  }

  ::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
    background-color: #304156;
  }

  ::v-deep .el-dialog__body {
    padding: 0px 20px 30px;
  }
</style>
